package com.hmall.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author wangyoucheng
 * @date 2025/9/2
 * @description TOD0
 */
@Slf4j
//@Component
public class DemoGlobalFilter  implements GlobalFilter, Ordered {
    /**
     * 过滤方法
     * @param exchange 用于获取Request和response对象
     * @param chain 过滤器链，用于放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径
        String path = request.getURI().getPath();
        System.out.println("path = " + path);
        //获取请求头
        String userAgent = request.getHeaders().getFirst("User-Agent");
        System.out.println("userAgent = " + userAgent);

        //如果要拦截。即立即响应
//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//        return response.setComplete();


        //如果要放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器的执行优先级
     * @return 整数值，值越小，过滤器执行的越早
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
